package beautiful.butterfly;

import beautiful.butterfly.server.httpserver.mvc.aop.AllowNotLogin;
import beautiful.butterfly.server.httpserver.mvc.core.ActionContext;
import beautiful.butterfly.server.httpserver.mvc.core.Controller;
import beautiful.butterfly.server.httpserver.mvc.core.annotation.actionbind.ActionKey;
import beautiful.butterfly.server.httpserver.mvc.multipart.FileItem;
import beautiful.butterfly.server.httpserver.mvc.render.Render;
import beautiful.butterfly.server.httpserver.mvc.render.TextRender;
import beautiful.butterfly.server.httpserver.mvc.render.VelocityRender;
import io.netty.handler.codec.http.Cookie;
import io.netty.handler.codec.http.DefaultCookie;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

@ActionKey("/index")
public class Test extends Controller {
    @AllowNotLogin
    public Render hello() {


        System.out.println("cookie" + ActionContext.getRequest().getClientNameToCookieMap());
        setSessionAttribute("xxx", "9999");
        System.out.println(getSessionAttribute("xxx"));
        Cookie cookies = new DefaultCookie("okm", "xx" + System.currentTimeMillis());
        ActionContext.getRequest().setCookie(cookies);
        return new TextRender("hello");
    }

    @AllowNotLogin
    public Render world() {
        setAttribute("hello", "你好");
        setAttribute("world", "世界");
        List<String> list = new ArrayList<String>();
        list.add("测试1");
        list.add("测试2");
        setAttribute("list", list);
        return new VelocityRender("/hellovelocity.vm");
    }


    @AllowNotLogin
    public Render index() {
        return new VelocityRender("/index.vm");
    }


    @AllowNotLogin
    public Render file() throws Exception {
        FileItem fileItem = ActionContext.getRequest().getFileNameToFileItemMap().get("ok");
        if (fileItem != null) {
            System.out.println(fileItem.getFileName());
            ;
            File file = new File("xxxx.tt");
            System.out.println(file.getAbsolutePath());
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(fileItem.getData(), 0, fileItem.getData().length);
            fileOutputStream.flush();
            fileOutputStream.close();
        }
        return new TextRender("ok");
    }
}